package com.sdry.web.controller.cb;


import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import com.sdry.service.cb.QuartzService;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.TriggerKey;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sdry.model.cb.JobDto;
import com.sdry.model.cb.TableDataInfo;
import com.sdry.utils.ResponseUtil;


@Controller
@RequestMapping("/systemTask")
public class SystemTaskController extends BaseController {

    @Autowired
    private Scheduler quartzScheduler;

    @Autowired
    private QuartzService quartzService;

    /**
     * 页面
     * @return
     */
    @RequestMapping("page")
    public String index() {
        return "/cb/systemTask";
    }

    @RequestMapping("list")
    @ResponseBody
    public TableDataInfo getJobList() throws SchedulerException {
        List<JobDto> jobInfos = this.getSchedulerJobInfo();
        return getDataTable(jobInfos,100);
    }

    /**
     * 创建定时任务
     */
    @RequestMapping("sendQQMail")
    @ResponseBody
    public void sendQQMail(String triggerName,String triggerGroupName,String cron,HttpServletResponse response){
    	int flg = 0;
        try {
            // 获取调度器
            Scheduler sched = quartzScheduler;
            // 创建一项作业
            JobDetail job = JobBuilder.newJob(RemindUserJob.class).withIdentity(triggerName,triggerGroupName).build();
            // 创建一个触发器
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerName,triggerGroupName).withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
            // 告诉调度器使用该触发器来安排作业
            sched.scheduleJob(job, trigger);
            // 启动
            if (!sched.isShutdown()) {
                sched.start();
            }
            flg = 1;
            System.out.println("-------------发送邮件定时启动成功---------------");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        
        try {
			ResponseUtil.write(response,flg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

    }

    @RequestMapping("/updataTaskCronByTriggerNameAndTriggerGroupName")
    @ResponseBody
    public void updataTaskCronByTriggerNameAndTriggerGroupName(String triggerName,String triggerGroupName,String cron,HttpServletResponse response) {
    	int flg = 0;
    	test(triggerName,triggerGroupName,cron);
        System.out.println("-------------重启成功---------------");
        flg = 1;
        try {
			ResponseUtil.write(response,flg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    /**
     *  标准新建任务0/2 * * * * ?
     */
    @RequestMapping("/addJob")
    @ResponseBody
    public void addJob() {

        try {
            quartzService.addJob("库存结存","定时任务","每日执行","triggerGroupName3",StockTaskJob.class,"0 1 0 * * ?");
        }catch (Exception e){
            logger.error(e.getMessage());
        }
    }



    /**
     * 编辑job
     * 0 50 10 * * ?
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/edit")
    public void edit(String corn) {
        try {
            test("每日执行","triggerGroupName3","0 6 19 * * ?");
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        logger.info("------------重启成功-------------");
        System.out.println("-------------重启成功---------------");
    }

    public void test(String triggerName,String triggerGroupName,String cron) {

        try {
            TriggerKey triggerKey = TriggerKey.triggerKey(triggerName, triggerGroupName);
            CronTrigger trigger = (CronTrigger) quartzScheduler.getTrigger(triggerKey);
            if (trigger == null) {
                return;
            }
            String oldTime = trigger.getCronExpression();
            if (!oldTime.equalsIgnoreCase(cron)) {
                // 触发器
                TriggerBuilder<Trigger> triggerBuilder = TriggerBuilder.newTrigger();
                // 触发器名,触发器组
                triggerBuilder.withIdentity(triggerName, triggerGroupName);
                triggerBuilder.startNow();
                // 触发器时间设定
                triggerBuilder.withSchedule(CronScheduleBuilder.cronSchedule(cron));
                // 创建Trigger对象
                trigger = (CronTrigger) triggerBuilder.build();
                // 方式一 ：修改一个任务的触发时间
                quartzScheduler.rescheduleJob(triggerKey, trigger);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }

    private List<JobDto> getSchedulerJobInfo() throws SchedulerException {
        List<JobDto> jobInfos = new ArrayList<JobDto>();
        List<String> triggerGroupNames = quartzScheduler.getTriggerGroupNames();
        for (String triggerGroupName : triggerGroupNames) {
            Set<TriggerKey> triggerKeySet = quartzScheduler.getTriggerKeys(GroupMatcher.triggerGroupEquals(triggerGroupName));
            for (TriggerKey triggerKey : triggerKeySet) {
                Trigger t = quartzScheduler.getTrigger(triggerKey);
                if (t instanceof CronTrigger) {
                    CronTrigger trigger = (CronTrigger) t;
                    JobKey jobKey = trigger.getJobKey();
                    JobDetail jd = quartzScheduler.getJobDetail(jobKey);
                    JobDto jobInfo = new JobDto();
                    jobInfo.setJobName(jobKey.getName());
                    jobInfo.setJobGroupName(jobKey.getGroup());
                    jobInfo.setTriggerName(triggerKey.getName());
                    jobInfo.setTriggerGroupName(triggerKey.getGroup());
                    jobInfo.setCronExpression(trigger.getCronExpression());
                    jobInfo.setNextFireTime(trigger.getNextFireTime());
                    jobInfo.setPreviousFireTime(trigger.getPreviousFireTime());
                    jobInfo.setStartTime(trigger.getStartTime());
                    jobInfo.setEndTime(trigger.getEndTime());
                    jobInfo.setJobClass(jd.getJobClass().getCanonicalName());
                    // jobInfo.setDuration(Long.parseLong(jd.getDescription()));
                    Trigger.TriggerState triggerState = quartzScheduler.getTriggerState(trigger.getKey());
                    jobInfo.setJobStatus(triggerState.toString());// NONE无,
                    // NORMAL正常,
                    // PAUSED暂停,
                    // COMPLETE完全,
                    // ERROR错误,
                    // BLOCKED阻塞
                    JobDataMap map = quartzScheduler.getJobDetail(jobKey).getJobDataMap();
                    if (null != map && map.size() != 0) {
                        jobInfo.setCount(Long.valueOf((String) map.get("count")));
                        jobInfo.setJobDataMap(map);
                    } else {
                        jobInfo.setJobDataMap(new JobDataMap());
                    }
                    jobInfos.add(jobInfo);
                }
            }
        }
        return jobInfos;
    }

}
